<template>
  <div class="goodsAdd-wrapper">
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/about' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片部分 -->
    <el-card>
      <!-- 顶部alert提示信息 -->
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>

      <!-- 横向steps -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="商品完成"></el-step>
      </el-steps>

      <!-- 竖向tabs -->
      <el-form :model="ruleForm" :rules="rules" label-position="top">
        <el-tabs
          :before-leave="beforeLeave"
          @tab-click="tabClick"
          v-model="activeIndex"
          tab-position="left"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="ruleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格">
              <el-input v-model="ruleForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="ruleForm.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="ruleForm.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="ruleForm.goods_cat"
                :options="catList"
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id',
                  children: 'children',
                }"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 复选框外层 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyList"
              :key="item.attr_id"
            >
              <!-- 复选框内层 -->
              <el-checkbox
                :label="subItem"
                @change="handleCheck(item.attr_id, subItem, $event)"
                border
                v-for="(subItem, i) in item.attr_vals"
                :key="i"
              ></el-checkbox>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyList"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :headers="headers"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="ruleForm.goods_introduce"> </quill-editor>
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 预览图片dialog -->
    <el-dialog width="50%" title="预览图片" :visible.sync="imgVisible">
      <img :src="imgUrl" alt="" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  name: "goodsAdd",
  data() {
    return {
      // 基本信息相关
      activeIndex: "0",
      catList: [], //商品分类列表
      ruleForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        attrs: [],
        pics: [],
      },
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "change" },
        ],
      },
      manyList: [], //动态参数列表
      onlyList: [], //静态属性列表
      // 商品图片相关
      uploadUrl: "http://heima.9yuecloud.com:9988/api/private/v1/upload",
      imgUrl: "",
      imgVisible: false,
      headers: {
        Authorization: localStorage.getItem("token"),
      },
    };
  },
  created() {
    this.GetGoodAdd();
  },
  methods: {
    handleEdit() {},
    // 渲染商品分类列表
    async GetGoodAdd() {
      let { data: res } = await this.$axios({
        url: "/api/private/v1/categories",
        method: "GET",
        params: { type: 3 },
      }).catch((err) => err);
      // console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("商品列表请求失败");
      this.catList = res.data;
    },
    // tabs跳转之前
    beforeLeave() {
      if (this.ruleForm.goods_cat.length == 0) {
        this.$message.error("请选择商品分类");
        return false;
      } else {
        return true;
      }
    },
    // 选择动态属性的复选框
    handleCheck(attr_id, attr_value, e) {
      // console.log(attr_id, attr_value, e);
      if (e) {
        this.ruleForm.attrs.push({ attr_id, attr_value, e });
      } else {
        let index = this.ruleForm.attrs.findIndex(
          (item) => item.attr_value == attr_value
        );
        this.ruleForm.attrs.splice(index, 1);
      }
    },
    // 点击tab
    async tabClick() {
      if (this.activeIndex == 1) {
        // 请求动态参数列表
        let { data: res } = await this.$axios({
          url: `/api/private/v1/categories/${this.ruleForm.goods_cat[2]}/attributes`,
          params: { sel: "many" },
        }).catch((err) => err);
        // console.log(res);
        if (res.meta.status !== 200)
          return this.$message.error("请求动态参数错误");

        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length == 0 ? [] : item.attr_vals.split(" ");
        });
        this.manyList = res.data;
      } else if (this.activeIndex == 2) {
        // 请求静态属性列表
        let { data: res } = await this.$axios({
          url: `/api/private/v1/categories/${this.ruleForm.goods_cat[2]}/attributes`,
          params: { sel: "only" },
        }).catch((err) => err);
        // console.log(res);
        if (res.meta.status !== 200)
          return this.$message.error("请求静态属性错误");
        this.onlyList = res.data;
      }
    },
    // 图片上传成功
    handleSuccess(res) {
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error("图片上传失败");
      let obj = { pic: res.data.tmp_path };
      this.ruleForm.pics.push(obj);
    },
    // 删除图片
    handleRemove() {},
    // 预览图片
    handlePreview(file) {
      // console.log(file ,"预览");
      this.imgUrl = file.url;
      this.imgVisible = true;
    },
    // 添加商品
    async addGoods() {
      // 深拷贝
      let ruleForm = _.cloneDeep(this.ruleForm);
      ruleForm.goods_cat = ruleForm.goods_cat.join(",");

      // 把静态属性添加到ruleForm中
      let arr = this.onlyList.map((item) => {
        return { attr_id: item.attr_id, attr_value: item.attr_vals };
      });
      ruleForm.attrs.push(...arr);
      this.$router.push("/goods");
      // 请求接口
      let { data: res } = await this.$axios({
        url: "/api/private/v1/goods",
        method: "POST",
        data: ruleForm,
      }).catch((err) => err);
      console.log(res);
    },
  },
};
</script>

<style lang="scss" scoped>
.goodsAdd-wrapper {
  .el-card {
    margin-top: 20px;
    .el-steps {
      margin: 20px 0;
    }
    ::v-deep .ql-container.ql-snow {
      height: 180px;
      margin-bottom: 20px;
    }
  }
}
</style>